<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <!-- 操作区域 -->
      <div class="top-operate-default">
        <div class="search-item">
          <label>顾客搜索：</label>
          <el-select v-model="keywordType" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-input style="width: 220px;" v-model="keyword" placeholder="输入搜索内容"></el-input>
          <label class="mar-l-20">注册时间：</label>
          <el-date-picker
            v-model="starEndTime"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <label class="mar-l-20">批发权限：</label>
          <el-select v-model="wholesaleAuthority" placeholder="批发权限" clearable class="pad-l-10" style="width: 140px">
            <el-option label="开启" value="1"></el-option>
            <el-option label="关闭" value="0"></el-option>
          </el-select>
          <label class="mar-l-20">主播权限：</label>
          <el-select v-model="anchorAuthority" placeholder="主播权限" clearable class="pad-l-10" style="width: 140px">
            <el-option label="开启" value="1"></el-option>
            <el-option label="关闭" value="0"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <div class="tabs-box mar-t-15">
        <el-tabs type="card" v-model="activeName" class="member-list-tab" @tab-click="handleClick">
          <el-tab-pane :label="allName" name="0"></el-tab-pane>
          <el-tab-pane :label="publicName" name="2"></el-tab-pane>
          <el-tab-pane :label="shareName" name="1"></el-tab-pane>
        </el-tabs>
      </div>
      <!-- 全选、操作 -->
      <div>
        <div class="pad-t-15 pad-b-15 font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-20">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{multipleSelection.length}}项</div>
          <el-popover v-if="enterpriseConfig.memberPriceAuthority == 1" placement="bottom" width="180" trigger="click" v-model="visibleMemberFlag">
            <el-form class="pad-t-10">
              <el-form-item>
                <el-radio v-model="memberFlag" label="1">开启会员身份</el-radio>
                <el-radio v-model="memberFlag" label="0" class="mar-t-10">关闭会员身份</el-radio>
              </el-form-item>
            </el-form>
            <div>
              <el-button size="mini" @click="visibleMemberFlag = false">取消</el-button>
              <el-button type="primary" size="mini" @click="batchUpdateMember('1')">确定</el-button>
            </div>
            <el-button slot="reference" class="batch-btn" @click="setMemberFlag">设置会员身份</el-button>
          </el-popover>
          <!-- <el-button class="batch-btn mar-l-10" @click="batchUpdateMember('3')" v-if="enterpriseConfig.wholesaleAuthority === 1">开启批发权限</el-button> -->
          <el-button class="batch-btn  mar-l-10" @click="openCustomImport">导入自定义信息</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="memberList" @sort-change="sortChange" @selection-change="handleSelectionChange"
          v-loading="listLoading" element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header" row-class-name="default-row">
          <el-table-column width="55px" type="selection" ></el-table-column>
          <el-table-column min-width="240px" label="微客" prop="userInfo" fixed="left">
            <template slot-scope="scope">
              <div @click="handleUpdate(scope.row)" class="flex v-align-c cursor-p">
                <div v-if="enterpriseConfig.memberPriceAuthority == 1" class="vip-icon-box"><img v-if="scope.row.memberFlag == 1" :src="vipIcon" alt=""></div>
                <label><img :src="scope.row.avatar" class="user-avatar cursor-p" v-if="scope.row.avatar"></label>
                <div class="font-14 pad-l-10">
                  <div><span class="font-color-9">昵称：</span>{{scope.row.nickname}}</div>
                  <div><span class="font-color-9">手机：</span>{{scope.row.phone}}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="类型">
            <template slot-scope="scope">
              <span v-if="scope.row.shareType == 1">分销商</span>
              <span v-if="scope.row.shareType == 2">普通顾客</span>
            </template>
          </el-table-column>
          <el-table-column width="209px" label="注册时间" prop="createTime" sortable="custom" >
            <template slot-scope="scope">
              <span>{{scope.row.createTime}}</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="批发权限/主播权限">
            <template slot-scope="scope">
              <span>{{ scope.row.wholesaleAuthority == 1 ? '开启' : '关闭' }}/{{ scope.row.anchorAuthority == 1 ? '开启' : '关闭' }}</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="累计成交">
            <template slot-scope="scope">
              <span><span class="font-color-9">订单：</span>{{scope.row.dealOrderNum}}</span><br/>
              <span><span class="font-color-9">金额：</span>{{scope.row.dealOrderPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="累计分销">
            <template slot-scope="scope">
              <span><span class="font-color-9">订单：</span>{{scope.row.projectOrderNum}}</span><br/>
              <span><span class="font-color-9">金额：</span>{{scope.row.projectOrderPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="备注" prop="remarkName" >
          </el-table-column>
          <el-table-column width="140px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="handleUpdate(scope.row)">查看</el-button>
              <el-button type="text" size="medium" @click="editRemark(scope.row)">编辑备注</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"

          :current-page="memberListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="memberListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    
    <!-- 备注 -->
    <el-dialog title="备注" :visible.sync="remarkVisible" :close-on-press-escape="true" width="460px">
      <div style="padding:20px;">
        <el-input
          type="textarea"
          :rows="6"
          placeholder="请输入内容"
          v-model="memberRemark.remarkName">
        </el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRemark">确认</el-button>
        <el-button @click="remarkVisible = false">取消</el-button> 
      </div>
    </el-dialog>
 
    <!-- 导入自定义信息 -->
    <el-dialog width="600px" v-el-drag-dialog title="导入自定义信息" :visible.sync="customImportVisible">
      <custom-import :showFlag="customImportVisible" moduleCode="1001" @close="closeCustomImport"></custom-import>
    </el-dialog>

  </div>
</template>


<style lang="less" scoped>
  .user-avatar {
    width: 59px;
    height: 59px;
    display: block;
    border-radius: 50%;
  }
  .cursor-p {
    position: relative;
    .vip-icon-box {
      position: absolute;
      top: -4px;
      left: -7px;
      transform: rotate(308deg);
      z-index: 9;
      img {
        width: 20px;
      }
    }
  }
</style>

<script>
  import { getNameByPath } from '@/utils/get-name-by-path' // 不要删除，根据URL获取文件名
  import { pagingCustomerMember, enableDisable, bacthUpdate, bacthUpdateAuthority, doBindSubUser, saveMemberRemark, getBindSubUser, countCustomerMember } from '@/api/user/member'
  import { doNatureInWxaCode, updateDistributionType, getEnterprise } from '@/api/user/enterprise'
  import { getByEnterpriseId } from '@/api/user/enterprise'

  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import store from '@/store'
  import detail from '../../../components/Member/Detail'
  import customImport from '../../system/custom-form/components/custom-import'
  import { listEnterpeiseRole } from '@/api/system/role'
  import vipIcon from '@/assets/images/vip-icon.png'

  export default {
    name: getNameByPath(),
    components: {
      detail, customImport
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        vipIcon,
        basicStatus: '0',
        memberList: [],
        textCol: 'nickname',
        textValue: '',
        starEndTime: [],
        th_memberList: [],
        authFlagList: [],
        natureList: [],
        authFlagType: '',
        activeName: '0',
        total: null,
        distributionType: '',
        memberWholesaleAuthority: '',
        distributionSetupBoolean: false,
        setSubUserVisible: false,
        listLoading: true,
        financeVisible: false,
        remarkVisible: false,
        // 导入自定义信息visible
        customImportVisible: false,
        keywordTypeOld: '',
        allName: '全部',
        publicName: '普通顾客',
        shareName: '分销商',
        multipleSelection: [],
        memberListQuery: {
          currentPage: 1,
          size: 10
        },
        recruiterId: '',
        wholesaleAuthority: '',
        anchorAuthority: '',
        keywordType: 'nickname',
        keyword: '',
        options: [{
          value: 'nickname',
          label: '昵称'
        }, {
          value: 'phone',
          label: '手机号'
        }],
        member: {
          memberId: '',
          nickname: '',
          realName: '',
          nature: '',
          memberGrade: '',
          labelName: '',
          phone: '',
          taskRegisteredTime: '',
          authFlag: '',
          taskStatus: '',
          delFlag: '',
          enterpriseId: '',
          status: '0'
        },
        enterpriseConfig: {
          wholesaleAuthority: 0
        },
        subUser: {},
        subRoleList: [],
        rules: {
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' }
          ],
          subRoleId: [
            { required: true, message: '请选择角色', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入操作员姓名', trigger: 'blur' }
          ]
        },
        memberAuthority: {},
        memberRemark: {
          memberRemarkId: '',
          remarkType: 1,
          remarkName: '',
          memberId: '',
          userId: this.getEnterpriseId()
        },
        enterpriseWxaCode: '',
        natureStyleMap: {
          0: 'font-yellow',
          1: 'font-blue',
          2: 'font-green'
        },
        authFlagStyleMap: {
          0: 'font-orange',
          1: 'font-green'
        },
        allChecked: false,
        visibleMemberFlag: false,
        memberFlag: '0'
      }
    },
    // 过滤器
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    // 初始化页面
    created() {
      this.queryParams = this.getCurrentPage().query
      if (this.queryParams && this.queryParams.recruiterId) {
        this.recruiterId = this.queryParams.recruiterId.toString()
      }
      this.initConfig()
      this.initMemberList()
      this.listEnterpeiseRole()
    },
    methods: {
      initCountMember(query) {
        this.allName = '全部'
        this.publicName = '普通顾客'
        this.shareName = '分销商'
        countCustomerMember(query).then(response => {
          if (response.isError) return
          this.allName += '(' + Math.floor(response.data.allNum) + '）'
          this.publicName += '(' + Math.floor(response.data.publicNum) + '）'
          this.shareName += '(' + Math.floor(response.data.shareNum) + '）'
        })
      },
      initConfig() {
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          this.enterpriseConfig = response.data
        })
      },
      listEnterpeiseRole() {
        listEnterpeiseRole({ enterpriseId: this.getEnterpriseId(), memberFlag: 1 }).then(response => {
          if (response.isError) return
          this.subRoleList = response.data
        })
      },
      initMemberList() {
        this.listLoading = true
        const query = {}
        query['currentPage'] = this.memberListQuery.currentPage
        query['size'] = this.memberListQuery.size
        if (this.starEndTime && this.starEndTime.length > 0) {
          query['startDate'] = this.starEndTime[0]
          query['endDate'] = this.starEndTime[1]
        }
        query['enterpriseId'] = this.getEnterpriseId()
        query['shareType'] = this.activeName
        query['recruiterId'] = this.recruiterId
        query['wholesaleAuthority'] = this.wholesaleAuthority
        query['anchorAuthority'] = this.anchorAuthority
        query['authFlag'] = this.authFlagType
        query[this.keywordType] = this.keyword
        this.initCountMember(query)
        pagingCustomerMember(query).then(response => {
          if (response.isError) return
          this.memberList = response.data.records
          if (this.memberList) {
            for (let i = 0; i < this.memberList.length; i++) {
              this.memberList[i].userInfo = {}
              this.memberList[i].userInfo.avatar = this.memberList[i].avatar
              this.memberList[i].userInfo.nickname = this.memberList[i].nickname
              this.memberList[i].userInfo.realName = this.memberList[i].realName
              this.memberList[i].natureStyle = this.natureStyleMap[this.memberList[i].nature]
              this.memberList[i].authFlagStyle = this.authFlagStyleMap[this.memberList[i].authFlag]
            }
          }
          if (this.memberList != null && this.memberList.length > 0) {
            if (response.data.dict.authFlag != null) {
              this.authFlagList = response.data.dict.authFlag
              this.authFlagList[''] = '实名状态'
            }
            if (response.data.dict.nature != null) {
              this.natureList = response.data.dict.nature
            }
          }
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // 列表排序
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'createTime') {
          if (order === 'ascending') {
            this.memberListQuery.ascs = 'createTime'
            this.memberListQuery.descs = ''
          } else {
            this.memberListQuery.ascs = ''
            this.memberListQuery.descs = 'createTime'
          }
        }
        this.initMemberList()
      },
      handleClick() {
        this.memberListQuery.currentPage = 1
        this.initMemberList()
      },
      handleClickBasic() {
      },
      handleSearch() {
        this.memberListQuery.currentPage = 1
        this.initMemberList()
      },
      resetSearch() {
        this.searchReset()
        this.initMemberList()
      },
      searchReset() {
        this.keywordType = 'nickname'
        this.keyword = ''
        this.wholesaleAuthority = ''
        this.anchorAuthority = ''
        this.starEndTime = []
        this.memberListQuery = {
          currentPage: 1,
          size: 10,
          startDate: null,
          endDate: null,
          nature: '',
          taskStatus: '',
          authFlag: '',
          wholesaleAuthority: ''
        }
      },
      handleSizeChange(val) {
        this.memberListQuery.size = val
        this.initMemberList()
      },
      handleCurrentChange(val) {
        this.memberListQuery.currentPage = val
        this.initMemberList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        this.th_memberList = []
        if (this.multipleSelection.length === this.memberList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 添加内部微客
      handleCreate() {
        const data = {
          enterpriseId: this.getEnterpriseId()
        }
        doNatureInWxaCode(data).then(response => {
          if (response.isError) return
          this.enterpriseWxaCode = response.data
          this.financeVisible = true
        })
      },
      // 设置账户
      bindSubUser(row) {
        getBindSubUser(row.memberId).then(response => {
          if (response.isError) return
          this.subUser = response.data
          this.subUser.status = this.subUser.status ? this.subUser.status + '' : '1'
          this.subUser.nickname = row.nickname
          this.subUser.memberId = row.memberId
          this.setSubUserVisible = true
        })
      },
      // 设置账户
      editRemark(row) {
        this.memberRemark.memberRemarkId = row.memberRemarkId
        this.memberRemark.memberId = row.memberId
        this.memberRemark.remarkName = row.remarkName
        this.memberRemark.remarkType = '4'
        this.memberRemark.userId = this.getEnterpriseId()
        this.remarkVisible = true
      },
      submitRemark() {
        saveMemberRemark(this.memberRemark).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.remarkVisible = false
          this.initMemberList()
        })
      },
      // 设置账户
      doBindSubUser() {
        this.$refs['subUser'].validate((valid) => {
          if (valid) {
            this.subUser.enterpriseId = this.getEnterpriseId()
            doBindSubUser(this.subUser).then(response => {
              if (response.isError) return
              this.$message({
                type: 'success',
                message: '成功!'
              })
              this.setSubUserVisible = false
            })
          }
        })
      },
      // 详情
      handleUpdate(row) {
        this.$router.push({ path: '/user/member-customer/details/index', query: { customerMemberId: row.memberId, enterpriseId: this.getEnterpriseId() }})
      },
      distributionSetup() {
        getEnterprise(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          if (response.data.distributionType === 0) {
            this.distributionType = false
          }
          if (response.data.distributionType === 1) {
            this.distributionType = true
          }
          if (response.data.memberWholesaleAuthority === 0) {
            this.memberWholesaleAuthority = false
          }
          if (response.data.memberWholesaleAuthority === 1) {
            this.memberWholesaleAuthority = true
          }
          this.basicStatus = '0'
          this.distributionSetupBoolean = true
        })
      },
      saveDistributionType() {
        let type = 0
        if (this.distributionType === true) {
          type = 1
        }
        let memberType = 0
        if (this.memberWholesaleAuthority === true) {
          memberType = 1
        }
        const data = {
          enterpriseId: this.getEnterpriseId(),
          distributionType: type,
          memberWholesaleAuthority: memberType
        }
        updateDistributionType(data).then(response => {
          if (response.isError) return
          this.$message({
            message: '成功',
            type: 'success'
          })
          this.distributionSetupBoolean = false
        })
      },
      // 更新
      handleUpdateStatus(row, status) {
        this.resetMember()
        this.member = Object.assign(this.member, row)
        this.member.taskStatus = status
        let name = ''
        if (status === 2) {
          name = '禁用成功!'
        } else {
          name = '启用成功!'
        }
        enableDisable(this.member).then((response) => {
          if (response.isError) return
          this.$message({
            type: 'success',
            message: name
          })
          this.initMemberList()
        })
      },
      isDisabled(row) {
        // 不能锁定、删除自己
        return row.username === store.getters.username
      },
      // 重置member
      resetMember() {
        this.member = {
          memberId: '',
          nickname: '',
          realName: '',
          nature: '',
          memberGrade: '',
          labelName: '',
          phone: '',
          taskRegisteredTime: '',
          authFlag: '',
          taskStatus: '',
          delFlag: ''
        }
      },
      // 设置会员身份
      setMemberFlag() {
        if (!this.multipleSelection.length) {
          this.$message.error('请选择要操作的数据')
          setTimeout(() => {
            this.visibleMemberFlag = false
          }, 20)
          return
        }
      },
      // 批量操作
      batchUpdateMember(command) {
        if (!this.multipleSelection.length) {
          this.$message.error('请选择要操作的数据')
          return
        }
        if (command === '1') {
          this.multipleSelection.forEach((item) => {
            this.resetMember()
            this.member.memberId = item.memberId
            this.member.memberFlag = this.memberFlag
            this.th_memberList.push(this.member)
          })
          bacthUpdate(this.th_memberList).then(response => {
            if (response.isError) return
            this.visibleMemberFlag = false
            this.initMemberList()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        } else {
          this.multipleSelection.forEach((item) => {
            this.memberAuthority = {}
            this.memberAuthority.memberId = item.memberId
            this.memberAuthority.enterpriseId = this.getEnterpriseId()
            this.memberAuthority.wholesaleAuthority = 1
            this.th_memberList.push(this.memberAuthority)
          })
          bacthUpdateAuthority(this.th_memberList).then(response => {
            if (response.isError) return
            this.initMemberList()
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          })
        }
        this.th_memberList = []
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.memberList.length) {
          this.memberList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 导入自定义信息打开事件
      openCustomImport() {
        this.customImportVisible = true
      },
      // 导入自定义信息关闭事件
      closeCustomImport() {
        this.customImportVisible = false
        this.initMemberList()
      }
    }
  }
</script>
